<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      :model="formData"
      ref="formRef"
      :rules="formRules"
      vloading="formLoading"
      label-width="auto"
    >
      <el-row>
        <el-col :offset="6" :span="24">
          <el-form-item label="拥有人" prop="ownerId">
            <el-select v-model="formData.ownerId" placeholder="请输入拥有人">
              <el-option
                v-for="dict in ownerList"
                :key="dict.id"
                :label="dict.nickname"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup name="CustomerTransfer" lang="ts">
import type { FormRules } from 'element-plus'
import * as UserApi from '@/api/system/user/user'
import * as CustomerApi from '@/api/customer/customer'
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const formLoading = ref(false)
const dialogTitle = ref('客户移交')
const dialogVisible = ref(false)
const formRef = ref()
interface RuleForm {
  ownerId: number
}
const formData = ref({
  id: undefined,
  ownerId: undefined
})
const formRules = ref<FormRules<RuleForm>>({
  ownerId: [{ required: true, message: '请选择所属人', trigger: 'change' }]
})
const oldOwnerId = ref()
const ownerList = ref()

/** 打开弹窗 */
const open = async (customerInfo) => {
  ownerList.value = await UserApi.getOwnerUser()
  formData.value = customerInfo
  oldOwnerId.value = customerInfo.ownerId
  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async () => {
  // 校验
  if (!formRef) return
  await formRef.value.validate()
  await CustomerApi.transfer(formData.value)
  message.success(t('common.createSuccess'))
  dialogVisible.value = false
  emit('success')
}
</script>
